<template>
  <div>
    <el-dialog 
      :title="title" 
      v-model="dialogVisible" 
      width="800px" 
      append-to-body 
      @opened="modalOpened"  
      @close="closeDialog"
    >
      <el-row>
        <el-col :xs="24" :md="12" :style="{height: '350px'}">
          <vue-cropper
            ref="cropper"
            :img="options.img"
            :info="true"
            :autoCrop="options.autoCrop"
            :autoCropWidth="options.autoCropWidth"
            :autoCropHeight="options.autoCropHeight"
            :fixedBox="options.fixedBox"
            :outputType="options.outputType"
            @realTime="realTime"
            v-if="dialogVisible"
          />
        </el-col>
        <el-col :xs="24" :md="12" :style="{height: '350px'}">
          <div class="avatar-upload-preview">
            <img :src="previews.url" :style="previews.img" />
          </div>
        </el-col>
      </el-row>
      <br />
      <el-row>
        <el-col :lg="2" :sm="3" :xs="3">
          <el-upload 
            action="#" 
            :http-request="requestUpload" 
            :show-file-list="false" 
            :before-upload="beforeUpload"
          >
            <el-button size="small">
              选择
              <i class="el-icon-upload el-icon--right"></i>
            </el-button>
          </el-upload>
        </el-col>
        <el-col :lg="{span: 1, offset: 2}" :sm="2" :xs="2">
          <el-button icon="el-icon-plus" size="small" @click="changeScale(1)"></el-button>
        </el-col>
        <el-col :lg="{span: 1, offset: 1}" :sm="2" :xs="2">
          <el-button icon="el-icon-minus" size="small" @click="changeScale(-1)"></el-button>
        </el-col>
        <el-col :lg="{span: 1, offset: 1}" :sm="2" :xs="2">
          <el-button icon="el-icon-refresh-left" size="small" @click="rotateLeft()"></el-button>
        </el-col>
        <el-col :lg="{span: 1, offset: 1}" :sm="2" :xs="2">
          <el-button icon="el-icon-refresh-right" size="small" @click="rotateRight()"></el-button>
        </el-col>
        <el-col :lg="{span: 2, offset: 6}" :sm="2" :xs="2">
          <el-button type="primary" size="small" @click="uploadImg()">提 交</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onUnmounted } from 'vue';
import { VueCropper } from "vue-cropper";
import { uploadFileApi } from '@/api/file';
import { updateProfileApi } from '@/api/user';
import { ElMessage } from 'element-plus';
import { useAuthStore } from '@/store'; // 导入 Pinia 仓库

// 定义 props
const props = defineProps({
  user: {
    type: Object,
    required: true
  },
  visible: {
    type: Boolean,
    default: false
  }
});

// 定义 emits
const emit = defineEmits(['update:visible', 'update-avatar']);

// 状态管理
const authStore = useAuthStore();
const dialogVisible = ref(props.visible);
const title = ref("修改头像");
const cropper = ref(null);
const resizeHandler = ref(null);

// 裁剪配置
const options = reactive({
  img: null,
  autoCrop: true,
  autoCropWidth: 200,
  autoCropHeight: 200,
  fixedBox: true,
  outputType: "png"
});

// 预览数据
const previews = ref({});

// 监听 visible 变化
watch(
  () => props.visible,
  (newVal) => {
    dialogVisible.value = newVal;
    if (newVal && props.user?.avatar) {
      options.img = props.user.avatar;
    }
  },
  { immediate: true }
);

// 清理事件监听
onUnmounted(() => {
  if (resizeHandler.value) {
    window.removeEventListener("resize", resizeHandler.value);
  }
});

// 方法定义
const editCropper = () => {
  emit('update:visible', true);
};

const modalOpened = () => {
  if (!resizeHandler.value) {
    resizeHandler.value = () => {
      refresh();
    };
    window.addEventListener("resize", resizeHandler.value);
  }
};

const refresh = () => {
  cropper.value?.refresh();
};

const requestUpload = () => {
  // 空实现，阻止默认上传行为
};

const rotateLeft = () => {
  cropper.value?.rotateLeft();
};

const rotateRight = () => {
  cropper.value?.rotateRight();
};

const changeScale = (num) => {
  num = num || 1;
  cropper.value?.changeScale(num);
};

const beforeUpload = (file) => {
  if (file.type.indexOf("image/") === -1) {
    ElMessage.error("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
    return false;
  }
  
  const reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = () => {
    options.img = reader.result;
  };
  return false; // 阻止默认上传
};

const uploadImg = async () => {
  if (!cropper.value) return;
  
  cropper.value.getCropBlob(async (data) => {
    const file = new File([data], 'avatar.jpg', { type: 'image/jpg' });
    const formData = new FormData();
    formData.append("file", file);
    
    try {
      // 上传文件
      const response = await uploadFileApi(formData, 'avatar');
      if (response.data) {
        // 更新用户头像
        await updateProfileApi({ 
          id: props.user.id, 
          avatar: response.data 
        });
        
        // 关闭对话框
        emit('update:visible', false);
        ElMessage.success('头像更新成功');
        
        // 更新全局状态
        if (authStore.userInfo) {
          authStore.userInfo.avatar = response.data;
        }
        
        // 通知父组件
        emit('update-avatar', response.data);
      }
    } catch (error) {
      ElMessage.error(error.message || '头像更新失败');
    }
  });
};

const realTime = (data) => {
  previews.value = data;
};

const closeDialog = () => {
  options.img = null;
  emit('update:visible', false);
  if (resizeHandler.value) {
    window.removeEventListener("resize", resizeHandler.value);
  }
};
</script>

<style scoped lang="scss">
.avatar-upload-preview {
  position: relative;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 200px;
  height: 200px;
  border-radius: 50%;
  box-shadow: 0 0 4px #ccc;
  overflow: hidden;
}
</style>
